package cn.edu.ujs.coor.service;

import cn.edu.ujs.coor.common.exception.CoorException;
import cn.edu.ujs.coor.model.Node;
import cn.edu.ujs.coor.repository.node.NodeRepository;
import cn.edu.ujs.coor.repository.relation.AccessRepository;
import cn.edu.ujs.coor.request.IdRequest;
import cn.edu.ujs.coor.request.node.NodeUpdateRequest;
import cn.edu.ujs.coor.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class NodeService extends BaseService<Node, Node> {

    @Autowired
    private AccessRepository accessRepository;

    @Autowired
    public void setRepository (NodeRepository repository) {
        this.repository = repository;
    }

    public List<Node> findAllSort () {
        Sort sort = new Sort(Sort.Direction.ASC, "sort");
        return this.repository.findAll(sort);
    }

    public void update (NodeUpdateRequest request) {
        Node node = this.findById(request.getId());
        if (node == null) {
            throw new CoorException("er_000002", "该节点信息不存在");
        }
        BeanUtil.copyBeanIgnoreNull(node, request);
        this.save(node);
    }

    /**
     * 删除节点信息
     * @param request
     */
    public void delete (IdRequest request) {
        Node node = this.findById(request.getId());
        if (node == null) {
            throw new CoorException("er_000002", "该节点信息不存在");
        }
        // 删除节点权限关联
        accessRepository.deleteByNodeId(request.getId());
        // 删除节点记录
        this.delete(node);
    }
}